package com.choosefine.base.shixiaobao.common.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;

/**
 * Created by Administrator on 2016/12/22.
 */
@Component
public class CommonUtil {
	
	/**
	 * bean转化为json
	 * 如果bean中有null值的话，可用此方法返回同bean中原样的字段个数
	 * 
	 * @param object
	 * @return
	 */
	public static String beanToJson(Object object){
		ObjectMapper om = new ObjectMapper();
		try {
			return om.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    /**
     * map拼接url
     * @param ymlUrl
     * @param dataMap
     * @return
     */
    public String getUrl(String ymlUrl, Map<String, Object> dataMap) {
        String url = "";
        if (dataMap == null) {
            return ymlUrl;
        }
        url += ymlUrl +"?";
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            url += entry.getKey() + "=" + entry.getValue() + "&";
        }
        url = url.substring(0, url.length() - 1);
        return url;
    }

    /**
     * bean拼接url
     * @param ymlUrl
     * @param object
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public String getUrl(String ymlUrl, Object object) throws InvocationTargetException, IllegalAccessException {
        String url = "";
        if (object == null) {
            return ymlUrl;
        }
        url += ymlUrl + "?";

        Class<?> actualEditable = object.getClass();
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            Object value = targetPd.getReadMethod().invoke(object);
            if(value instanceof List){
                value = Joiner.on(",").join((List)value);
            }
            if (!"class".equals(targetPd.getName()) && value != null) {
                url += targetPd.getName() + "=" + value + "&";
            }
        }
        url = url.substring(0, url.length() - 1);
        return url;
    }

    public MultiValueMap<String, String> beanToMultiValueMap(Object obj) throws Exception {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        try {
            Class<?> actualEditable = obj.getClass();
            PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
            for (PropertyDescriptor targetPd : targetPds) {
                Method readMethod = targetPd.getReadMethod();
                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                    readMethod.setAccessible(true);
                }
                String name = targetPd.getName();
                Object value = readMethod.invoke(obj);
                if(value != null){
                    if (value instanceof Date) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        value = simpleDateFormat.format((Date)value);
                    }
                    if(!(value instanceof Class)) {
                        params.add(targetPd.getName(), value.toString());
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("参数转化出错");
        }
        return params;
    }

    public Map<String, Object> beanToMap(Object obj) throws Exception {
        Map<String, Object> params = new HashMap<>(0);
        try {
            Class<?> actualEditable = obj.getClass();
            PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
            for (PropertyDescriptor targetPd : targetPds) {
                Method readMethod = targetPd.getReadMethod();
                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                    readMethod.setAccessible(true);
                }
                String name = targetPd.getName();
                Object value = readMethod.invoke(obj);
                if(value != null){
                    if (value instanceof DateTime) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        value = simpleDateFormat.format((Date)value);
                    }
                    if (value instanceof Date) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        value = simpleDateFormat.format((Date)value);
                    }
                    if(!(value instanceof Class)){
                        params.put(targetPd.getName(), value.toString());
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("参数转化出错");
        }
        return params;
    }
}
